package com.cloudxingkong.dianyinke.Student.Ui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.Toast;

import com.cloudxingkong.dianyinke.NewTeacher.Utils.CookieHelper;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.LoginJsonUtils;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.NoScrollGridView;
import com.cloudxingkong.dianyinke.NewTeacher.Utils.PhotoUtils;
import com.cloudxingkong.dianyinke.R;
import com.cloudxingkong.dianyinke.Student.Adapter.ComAdapter;
import com.cloudxingkong.dianyinke.Uri.studentUri.StudentUri;
import com.cloudxingkong.dianyinke.Uri.teacherUri.ThisUri;

import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import me.nereo.multi_image_selector.MultiImageSelectorActivity;


/**
 * @评论Activity
 * @name:Zxrui
 */
public class Comment extends AppCompatActivity {

    private EditText editText_opinion;
    private String opinoin;
    private NoScrollGridView gridView;
    private RatingBar ratingBar_comment;
    private SharedPreferences sharedPreferences;
    private ProgressDialog progressDialog;
    private boolean flag=false;
    private int score=-1;
    private ArrayList<String> pathList;
    private static final int REQUEST_IMAGE=2;
    private ComAdapter adapter;
    private List<Bitmap> imgList=new ArrayList<>();
    private static final int SELECT_PIC_BY_TAKE_PHOTO=1;
    private static final int SELECT_PIC_BY_PICK_PHOTO=2;
    private String id;
    private String lessonid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_comment);
        init();
        gridView.setAdapter(adapter);

    }


    private void init() {
        gridView = (NoScrollGridView) findViewById(R.id.gridView);
        editText_opinion = ((EditText) findViewById(R.id.editText_opinion));
        ratingBar_comment= ((RatingBar) findViewById(R.id.ratingBar_comment));
        sharedPreferences=getSharedPreferences("data_dyk",0);
        adapter = new ComAdapter(this,imgList);
        Intent intent = getIntent();
        id = intent.getStringExtra("id");
        lessonid = intent.getStringExtra("lessonid");
    }

    public void back(View view){
        switch (view.getId()){
            case R.id.btn_tiJiao:
                if (TextUtils.isEmpty(editText_opinion.getText())) {
                    Toast.makeText(this, "内容不完整...", Toast.LENGTH_SHORT).show();
                }else {
                    if (ratingBar_comment.getRating()==0){
                        Toast.makeText(Comment.this, "您还未评分", Toast.LENGTH_SHORT).show();
                        return;
                    }else{
                        score = (int) ratingBar_comment.getRating();
                    }
                    progressDialog = ProgressDialog.show(this, null, "正在为您提交评价...", true, false);
                    opinoin = editText_opinion.getText().toString();


                    final String sessionid = CookieHelper.getSessionID(sharedPreferences);
                    final String upLoadUrl = ThisUri.SERVER_YUMING+ StudentUri.COMMENT;

                    RequestParams params = new RequestParams(upLoadUrl);
                    params.setHeader("cookie", sessionid);
                    params.setMultipart(true);
                    params.addBodyParameter("evaluate", opinoin);
                    params.addBodyParameter("lessonid", id);

                    params.addBodyParameter("score",score+"");
                    if (pathList.size() != 0 && pathList != null) {

                        Log.e("test", "图片路径集合的大小 " + pathList.size());
                        if (pathList.size() > 0) {
                            params.addBodyParameter("pic1", new File(pathList.get(0)));
                            if (pathList.size()>1){
                                params.addBodyParameter("pic2", new File(pathList.get(1)));
                                if (pathList.size()>2){
                                    params.addBodyParameter("pic3", new File(pathList.get(2)));
                                    if (pathList.size() > 3) {
                                        params.addBodyParameter("pic4", new File(pathList.get(3)));
                                    }
                                }
                            }
                        }
                    }
                    x.http().post(params, new Callback.CommonCallback<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Log.e("test","上"+ result);
                            Message message = handler.obtainMessage();
                            message.what = 1;
                            message.obj = result;
                            handler.sendMessage(message);
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            progressDialog.dismiss();
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {

                        }

                        @Override
                        public void onFinished() {

                        }
                    });
                }
                break;
        }
    }
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    String state = (String) msg.obj;
                    Log.e("test", "评论结果：" + state);
                    HashMap<String, Object> jsonFromLogin = LoginJsonUtils.getJsonFromLogin(state);
                    flag = (boolean) jsonFromLogin.get("success");
                    if (flag){
                        Toast.makeText(Comment.this,"评论成功",Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                        finish();
                    }else {
                        Toast.makeText(Comment.this,"评论失败,请稍后重试!",Toast.LENGTH_SHORT).show();
                        progressDialog.dismiss();
                    }
                    break;

            }
        }
    };
    public void phion(View view) {
        int maxNum=4;
        Intent intent=new Intent(Comment.this,MultiImageSelectorActivity.class);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA,true);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT,maxNum);
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        if (pathList != null && pathList.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST,pathList);
        }
        startActivityForResult(intent, REQUEST_IMAGE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_IMAGE) {
            if (resultCode == Activity.RESULT_OK) {
                pathList=data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                for (String s : pathList) {
                    PhotoUtils photoUtils3 = new PhotoUtils();
                    PhotoUtils.CompressOptions options3=new PhotoUtils.CompressOptions();
                    options3.uri=Uri.fromFile(new File(s));
                    Bitmap bitmap3 = photoUtils3.compressFromUri(this, options3);
                    imgList.add(bitmap3);
                }
                adapter.notifyDataSetChanged();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
//    private void pickPhoto(){
//        Intent intent = new Intent();
//        intent.setType("image/*");
//        intent.setAction(Intent.ACTION_GET_CONTENT);
//        startActivityForResult(intent, SELECT_PIC_BY_PICK_PHOTO);
//    }
    public void back_back(View view) {
        finish();
    }
}


